// 自己封装的 uni.request 工具类
import wx from '@/components/jweixin-module/lib/index.js';
import request from './http.js';

class wxJsSdk {
	constructor() {
		this.isWechat()
	}

	//判断是否在微信中
	isWechat() {
		// #ifndef H5
		console.log('不是H5')
		return false;
		// #endif
		var ua = window.navigator.userAgent.toLowerCase();
		if (ua.match(/micromessenger/i) == 'micromessenger') {
			return true;
		} else {
			console.log('不是微信浏览器')
			return false;
		}
	}

	async config() {
		try {
			var ua = navigator.userAgent.toLowerCase();
			var signLink = ''
			if (/iphone|ipad|ipod/.test(ua)) {
				signLink = uni.getStorageSync("wurl");
				if (!signLink) signLink = location.href;
			} else {
				signLink = location.href;
			}

			const data = await request.sendRequest({
				url: 'Ajax/jssdk',
				data: {
					url: signLink
				},
			});
			const result = data.data.data
			wx.config({
				debug: result.debug,
				appId: result.appId,
				timestamp: result.timestamp,
				nonceStr: result.nonceStr,
				signature: result.signature,
				jsApiList: result.jsApiList
			});
			wx.ready(() => {
				console.log('JSSDK ready');
			});
			wx.error((res) => {});

		} catch (error) {
			console.error('JSSDK config failed:', error);
		}
	}
	// 封装scanQRCode接口
	scanQRCode(options) {
		wx.scanQRCode({
			...options,
			success: (res) => {
				console.log('Scan result:', res.result);
				if (options.success) options.success(res);
			},
			fail: (res) => {
				console.error('Scan QR code failed:', res);
				if (options.fail) options.fail(res);
			}
		});
	}
}

export default new wxJsSdk();